package com.jrx.anytxn.common.uitl;

import com.jrx.anytxn.common.exception.TxnArgumentException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * @ClassName BeanValidateUtils
 * @Description: 实体类属性校验工具类
 * @Author haopu.zheng
 * @Date 2019/7/22
 * @Version V1.0
 **/
public class BeanValidateUtils {
    /**
     * 校验实体类
     *
     * @param t
     * @return
     */
    public static <T>  void validate(T t) {
        //定义返回错误List
 /*       List<Map<String, String>> errList = new ArrayList<Map<String, String>>();
        static <T> List<Map<String, String>>

        Map<String, String> errorMap;*/

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

        Validator validator = factory.getValidator();

        Set<ConstraintViolation<T>> errorSet = validator.validate(t);
        if(errorSet !=null&&!errorSet.isEmpty()){
            StringBuilder errorMessage=new StringBuilder();
            for (ConstraintViolation<T> c : errorSet) {
                errorMessage.append(c.getPropertyPath().toString())
                        .append(c.getMessage())
                        .append(";");
            }
            throw new TxnArgumentException(errorMessage.toString());
        }
    }

}

